package com.dropdb.demo.service.impl;

import com.dropdb.demo.bean.Storage;
import com.dropdb.demo.bean.StorageExample;
import com.dropdb.demo.bean.bo.BaseData;
import com.dropdb.demo.mapper.StorageMapper;
import com.dropdb.demo.service.StorageService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;

@Service
public class StorageServiceImpl implements StorageService {
    @Autowired
    StorageMapper storageMapper;
    @Override
    public Storage insertStorageFile(MultipartFile file, String key, String url) {
        //构建文件对象
        Storage storage = new Storage();
        storage.setKey(key);
        storage.setName(file.getOriginalFilename());
        storage.setType(file.getContentType());
        storage.setSize((int) file.getSize());
        storage.setUrl(url);
        Date date = new Date();
        storage.setAddTime(date);
        storage.setUpdateTime(date);
        storage.setDeleted(false);
        //插入数据库
        storageMapper.insert(storage);
        storage.setDeleted(null);
        return storage;
    }

    @Override
    public BaseData<Storage> list(Integer page, Integer limit, String key, String name, String sort, String order) {
        StorageExample storageExample = new StorageExample();
        StorageExample.Criteria criteria = storageExample.createCriteria();
        if (null != key) {
            criteria.andKeyLike("%" + key + "%");
        }
        if (null != name) {
            criteria.andNameLike("%" + name + "%");
        }
        criteria.andDeletedEqualTo(false);
        PageHelper.startPage(page, limit);
        List<Storage> storages = storageMapper.selectByExample(storageExample);
        PageInfo<Storage> pageInfo = new PageInfo<>(storages);
        long total = pageInfo.getTotal();
        return new BaseData<>(total, storages);
    }

    @Transactional
    @Override
    public Storage update(Storage storage) {
        if (null == storage.getId() || null == storage.getName()) {
            return null;
        }
        Storage toDB = new Storage();
        toDB.setId(storage.getId());
        toDB.setName(storage.getName());
        //存在设置已删除元素的可能
        int i = storageMapper.updateByPrimaryKeySelective(toDB);
        if (1 != i) {
            return null;
        }
        return storage;
    }

    @Override
    public int delete(Storage storage) {
        if (null == storage.getId() || storage.getId() < 1) {
            return -1;
        }
        Storage toDB = new Storage();
        toDB.setId(storage.getId());
        toDB.setDeleted(true);
        return storageMapper.updateByPrimaryKeySelective(toDB);
    }
}
